package cn.studyjams.s1.contest.autohello;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cn.studyjams.s1.contest.autohello.model.User;
import cn.studyjams.s1.contest.autohello.utils.ImageLoader.BitmapUtils;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class UpdateProfileActivity extends BaseActivity implements
        View.OnClickListener,
        CameraOrPhotoFragment.PickPicListener {

    private static final String TAG = "UpdateProfileActivity";

    private static final int STORAGE_PERMS = 101;
    private static final int CAMERA = 102;
    private static final int PHOTO = 103;

    Uri mDownloadUrl = null;
    Uri photoURI = null;

    private EditText mUsernameET;
    private EditText mPhoneNumberET;
    private EditText mEmailET;
    private ImageView mHeadPicIV;

    private CoordinatorLayout snackBarHolder;

    private User user;

    private DatabaseReference mRef;
    private StorageReference mStorageRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_profile);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbarLayout.setTitle(getResources().getString(R.string.update_profile));

        mUsernameET = (EditText) findViewById(R.id.update_profile_username);
        mPhoneNumberET = (EditText) findViewById(R.id.update_profile_phone);
        mEmailET = (EditText) findViewById(R.id.update_profile_email);
        mHeadPicIV = (ImageView) findViewById(R.id.profile_head_pic);
        snackBarHolder = (CoordinatorLayout) findViewById(R.id.activity_update_profile);

        user = (User) getIntent().getSerializableExtra("user");

        mRef = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid());
        mStorageRef = FirebaseStorage.getInstance().getReference();

        mUsernameET.setText(user.getUsername());
        mPhoneNumberET.setText(user.getPhoneNumber());
        mEmailET.setText(user.getEmail());

        String photoUrl = user.getPhoto();
        if (photoUrl != null && !photoUrl.equals("")) {
            BitmapUtils bitmapUtils = new BitmapUtils();
            bitmapUtils.disPlay(mHeadPicIV, photoUrl);
            mHeadPicIV.setPadding(0, 0, 0, 0);
        }

        findViewById(R.id.profile_head_pic_btn).setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_update_profile, menu);
        return true;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_update) {

            if (isConnectedToNetwork()) {
                showProgressDialog(getString(R.string.update_profile));
                String username = mUsernameET.getText().toString();
                String phoneNumber = mPhoneNumberET.getText().toString();
                String email = mEmailET.getText().toString();

                if (!TextUtils.isEmpty(username)) {
                    user.setUsername(username);
                }

                if (!TextUtils.isEmpty(phoneNumber)) {
                    user.setPhoneNumber(phoneNumber);
                }

                if (!TextUtils.isEmpty(email)) {
                    user.setEmail(email);
                }

                if (photoURI != null) {
                    mProgressDialog.setMessage(getString(R.string.upload_image));

                    final StorageReference photoRef = mStorageRef.child(user.getUid())
                            .child(photoURI.getLastPathSegment());

                    photoRef.putFile(photoURI)
                            .addOnProgressListener(this, new OnProgressListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                                    String format = taskSnapshot.getBytesTransferred() + "/" + taskSnapshot.getTotalByteCount();
                                    mProgressDialog.setProgressNumberFormat(format);
                                }
                            }).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            if (taskSnapshot.getMetadata() != null) {
                                mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
                                if (mDownloadUrl != null) {
                                    user.setPhoto(mDownloadUrl.toString());
                                }
                                mRef.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        hideProgressDialog();
                                        finish();
                                    }
                                });
                            }
                        }
                    }).addOnFailureListener(this, new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {

                        }
                    });
                } else {
                    mRef.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            hideProgressDialog();
                            finish();
                        }
                    });
                }
            } else {
                Snackbar.make(snackBarHolder, getString(R.string.offline), Snackbar.LENGTH_LONG)
                        .show();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.profile_head_pic_btn) {
            CameraOrPhotoFragment pickPicFragment = new CameraOrPhotoFragment();
            pickPicFragment.show(getSupportFragmentManager(), "CameraOrPhoto");
        }
    }

    @AfterPermissionGranted(STORAGE_PERMS)
    @Override
    public void onCameraClick() {
        // Check that we have permission to read images from external storage.
        String perm = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        if (!EasyPermissions.hasPermissions(this, perm)) {
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage),
                    STORAGE_PERMS, perm);
            return;
        }

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                photoURI = FileProvider.getUriForFile(this,
                        "cn.studyjams.s1.contest.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, CAMERA);
            }
        } else {
            Snackbar.make(snackBarHolder, getString(R.string.no_camera_app), Snackbar.LENGTH_LONG).show();
        }
    }

    @AfterPermissionGranted(STORAGE_PERMS)
    @Override
    public void onPhotoClick() {
        // Check that we have permission to read images from external storage.
        String perm = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        if (!EasyPermissions.hasPermissions(this, perm)) {
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage),
                    STORAGE_PERMS, perm);
            return;
        }

        Intent albumIntent = new Intent(Intent.ACTION_PICK);

        if (albumIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                photoURI = FileProvider.getUriForFile(this,
                        "cn.studyjams.s1.contest.fileprovider",
                        photoFile);
                albumIntent.setType("image/*");
                albumIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(albumIntent, PHOTO);
            }
        } else {
            Snackbar.make(snackBarHolder, getString(R.string.no_photos_app), Snackbar.LENGTH_LONG).show();
        }
    }

    @Override
    public void onRemoveClick() {
        user.setPhoto("");
        mHeadPicIV.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_person_24dp));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA && resultCode == RESULT_OK) {
            if (photoURI != null) {
                mHeadPicIV.setImageURI(photoURI);
                mHeadPicIV.setPadding(0, 0, 0, 0);
            }
        }

        if (requestCode == PHOTO && resultCode == RESULT_OK) {
            if (data != null) {
                photoURI = data.getData();
                mHeadPicIV.setImageURI(photoURI);
                mHeadPicIV.setPadding(0, 0, 0, 0);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
                .format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        String mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private boolean isConnectedToNetwork() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }
}
